//
//  ICMessageVController.m
//  ICome
//
//  Created by Administrator on 2016/10/25.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICMessageVController.h"
#import "ICMessageVController+Notification.h"
#import "ICMessageVController+Delegate.h"
#import "ICMessageVController+Logic.h"

#import "ICTitleLoadingView.h"
#import "ICCommonGroup.h"
#import "ICNotify.h"
#import "ICSyncManager.h"

#import "UIButton+Extension.h"
#import "ICLoginNetworkManager.h"
#import "ICOrganizationViewController.h"
#import "ICSearchBar.h"

#import "iComeApiManager.h"

@interface ICMessageVController ()<UITableViewDataSource,UITableViewDelegate, ICPullComboBoxDelegate,UISearchControllerDelegate,UISearchBarDelegate,UISearchResultsUpdating,ICGroupSearchDelegate,ICShareDelegate>

@end

@implementation ICMessageVController

-(id)initWithRouterParams:(NSDictionary *)params {
    if (self = [super initWithRouterParams:params]) {
        [self initNotificationCenter];
    }
    return self;
}

#pragma mark -建立视图
- (void)setUI
{
    self.lastmessage = -1;
    self.definesPresentationContext = YES;
    
    self.tableView.backgroundColor = BACKGROUNDCOLOR;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top);
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    
    [self.tableView addSubview:self.emptyView];
    
    ICSearchBar *searchBar = [ICSearchBar searchBar];
    UIImage *image = [UIImage  imageNamedFromiComeSDKBundle:@"icon_search"];
    searchBar.iconImage.image = [image imageWithColor:[ICTools getRgbColor:0xc9c9c9]];
    searchBar.spaceLeftView.width = App_Frame_Width/2.0 - 17;
    
    searchBar.frame = CGRectMake(10, 10, App_Frame_Width - 20, 30);
    searchBar.userInteractionEnabled = NO;
    UIView *searchBackGroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, App_Frame_Width, 50)];
    [searchBackGroundView addSubview:searchBar];
    WEAKSELF
    UITapGestureRecognizer *searchTap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        NSLog(@"输出");
        ICGroupSearchController *searchVC = [[ICGroupSearchController alloc] init];
        searchVC.delegate  = weakSelf;
        [weakSelf.navigationController pushViewController:searchVC animated:YES];
    }];
    [searchBackGroundView addGestureRecognizer:searchTap];
    
    self.tableView.tableHeaderView = searchBackGroundView;
    
    // 先把mjrefresh加到tableview上，再加载searchbar到其tableview的头视图 - 顺序不能改变
    self.tableView.mj_header = [NSClassFromString(@"ICKRefreshHeader") headerWithRefreshingTarget:self refreshingAction:@selector(sync)];
    
    
    UIView *bView = [[UIView alloc] initWithFrame:self.tableView.frame];
    bView.backgroundColor = BACKGROUNDCOLOR;
    self.tableView.backgroundView = bView;
    [self setNavBackgroundColor:NE_BACKGROUND_COLOR];
    [self setNavShadowColor:NE_BACKGROUND_COLOR];
}

//- (void)leftBarButtonClicked {
//    UIViewController *viewController = [[IComMediator sharedInstance] IComMediator_MineViewController:nil];
//    [self.navigationController pushViewController:viewController animated:YES];
//}

-(void)sync
{
    [self.tableView.mj_header beginRefreshing];
    [ICNotification postNotificationName:NotificationUpdateGroupList object:nil userInfo:nil];
}


#pragma mark - 配置数据源

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNav];
    [self setUI];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self reloadDataSource];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithImageName:@"App_menubox_blue" itemType:UIBarButtonItemTypeRight target:self action:@selector(rightBarButtonClicked)];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.boxView close];
    [self.boxView removeFromSuperview];
    self.boxView = nil;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.hidesBottomBarWhenPushed = YES;
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.searchController setActive:NO];
}

#pragma mark - setter and getter
- (UITableView *)tableView
{
    if (!_tableView) {
        UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
        [self.view addSubview:tableView];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView = tableView;
    }
    return _tableView;
}
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return  _dataArray;
}

-(ICBaseSearchViewController *)searchController
{
    if(!_searchController){
        
        ICGroupSearchController *searchVC = [[ICGroupSearchController alloc] init];
        searchVC.delegate  = self;
        ICBaseSearchViewController *searchController = [[ICBaseSearchViewController alloc] initWithSearchResultsController:searchVC];
        searchController.placeholder = @"搜索";
        searchController.delegate = self;
        searchController.searchBar.delegate  = self;
        searchController.searchResultsUpdater = self;
        _searchController = searchController;  // 强指针引用
        
    }
    return _searchController;
}


-(ICPullComboBoxView *)boxView {
    if (!_boxView) {
        WEAKSELF
        ICComboxItem *contact = [ICComboxItem itemWithIcon:@"icon_contact_session"
                                                           title:@"单人会话"
                                                     destVcClass:nil
                                                       parameter:nil];
        contact.option = ^{
            if ([[iComeApiManager instance].delegate respondsToSelector:@selector(openContactsFromViewC:)]) {
                [[iComeApiManager instance].delegate openContactsFromViewC:weakSelf];
            } else {
                UIViewController *vc = [[IComMediator sharedInstance] IComMediator_ContactsViewController:nil];
                [weakSelf.navigationController pushViewController:vc animated:YES];
            }
        };
        
        ICComboxItem *creatEmpGroup = [ICComboxItem itemWithIcon:@"icon_peoples_session"
                                                           title:@"多人会话"
                                                     destVcClass:nil
                                                       parameter:nil];
        creatEmpGroup.option = ^{
            if ([[iComeApiManager instance].delegate respondsToSelector:@selector(createGroupUsersFromViewC::)]) {
                [[iComeApiManager instance].delegate createGroupUsersFromViewC:weakSelf :^(id result) {
                    NSLog(@"%@", result);
                    NSMutableArray *list = [[NSMutableArray alloc] init];
                    for (NSDictionary *dict in result) {
                        ICEmpInfoModel *model = [[ICEmpInfoModel alloc] init];
                        model.eId = dict[@"eId"];
                        model.eName = dict[@"eName"];
                        model.select = YES;
                        [list addObject:model];
                    }
                    NSDictionary *param = [ICCreateGroupManager createMultGroupParamWithUserList:list];
                    [ICCreateGroupManager createMultGroupWith:param Handle:^(ICGroup *group) {
                        ICChatViewController *vc = [[ICChatViewController alloc] init];
                        vc.group = group;
                        [weakSelf.navigationController pushViewController:vc animated:YES];
                    }];
                }];
            } else {
                ICOrganizationViewController *vc = [[ICOrganizationViewController alloc] init];
                vc.titleName = @"多人会话";
                vc.eId = [ICUser currentUser].eId;
                vc.CtrStyle = CtrStyleEmploye_sdk;
                vc.kkGroupType = GroupStyleCreateEmployee;
                vc.backFlag = @"2";
                [weakSelf.navigationController pushViewController:vc animated:YES];
            }
        };
        
        ICComboxItem *creatGroup = [ICComboxItem itemWithIcon:@"icon_department_session"
                                                        title:@"团队会话"
                                                  destVcClass:nil
                                                    parameter:nil];
        creatGroup.option = ^{
            if ([[iComeApiManager instance].delegate respondsToSelector:@selector(createGroupDepartmentFromViewC::)]) {
                [[iComeApiManager instance].delegate createGroupDepartmentFromViewC:weakSelf :^(id result) {
                    NSString *oId = [[result firstObject] objectForKey:@"oId"];
                    if ([ICTools stringEmpty:oId]) {
                        NSLog(@"oId不能为空");
                        return ;
                    }
                    NSDictionary *param = @{@"eId":[ICUser currentUser].eId,
                                            @"eName":[ICUser currentUser].eName,
                                            @"gName":[[result firstObject] objectForKey:@"gName"] == nil ? @"自定义群组名称":[[result firstObject] objectForKey:@"gName"],
                                            @"oId":[[result firstObject] objectForKey:@"oId"]};
                    [ICCreateGroupManager createOrgGroupWith:param Handle:^(ICGroup *group) {
                        ICChatViewController *vc = [[ICChatViewController alloc] init];
                        vc.group = group;
                        [self.navigationController pushViewController:vc animated:YES];
                    }];
                }];
            } else {
                ICOrganizationViewController *vc = [[ICOrganizationViewController alloc] init];
                vc.titleName = @"团队会话";
                vc.eId = [ICUser currentUser].eId;
                vc.CtrStyle = CtrStyleEmploye_sdk;
                vc.kkGroupType = GroupStyleCreateNode;
                vc.backFlag = @"2";
                [weakSelf.navigationController pushViewController:vc animated:YES];
            }
        };
        
        ICComboxItem *scan = [ICComboxItem itemWithIcon:@"icon_mine_scan"
                                                  title:@"扫一扫"
                                            destVcClass:nil
                                              parameter:nil];
        scan.option = ^{
            [ICSystemTool checkCameraAuthorizationStatus:^{
                
                UIViewController *viewController = [[IComMediator sharedInstance] IComMediator_RCodeViewController:nil handler:^(id result) {
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [weakSelf pushCustomViewControllerURL:result[@"url"] fromViewController:weakSelf animated:YES];
                    });
                }];
                [weakSelf.navigationController pushViewController:viewController animated:YES];
                //                ICNavigationController *nvc = [[ICNavigationController alloc] initWithRootViewController:viewController];
                //                [weakSelf presentViewController:nvc animated:YES completion:nil];
            }];
        };
        
        //        ICComboxItem *setting = [ICComboxItem itemWithIcon:@"icon_contacts_setting"
        //                                                     title:@"设置"
        //                                               destVcClass:nil
        //                                                 parameter:nil];
        ICCommonGroup *baseGroup = [[ICCommonGroup alloc] init];
        baseGroup.items = @[contact, creatEmpGroup, creatGroup, scan];
        
        _boxView = [[ICPullComboBoxView alloc] initWithFrame:CGRectMake(0, ([ICTools getStatusbarHeight] + [ICTools getNavbarHeight]), App_Frame_Width, APP_Frame_Height)];
        [_boxView.dataList addObject:baseGroup];
        [_boxView.tableView reloadData];
        _boxView.delegate = self;
        [self.view.window addSubview:_boxView];
    }
    return _boxView;
}

-(ICTitleLoadingView *)loading {
    if (!_loading) {
        _loading = [[ICTitleLoadingView alloc] initWithFrame:CGRectMake(0, 0, 200, 45)];
        _loading.titleLabel.text = @"消息";
        _loading.titleLabel.textColor = [UIColor whiteColor];
    }
    return _loading;
}

-(ICEmptyStyleView *)emptyView {
    if (!_emptyView) {
        _emptyView = [[ICEmptyStyleView alloc] initWithTitle:@"暂无数据" placeholderImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_message_empty"] imageURL:@""];
        _emptyView.hidden = YES;
        _emptyView.frame = CGRectMake(0, 50, App_Frame_Width, APP_Frame_Height);
    }
    return _emptyView;
}

#pragma mark - 响应事件
- (void)rightBarButtonClicked
{
    [self.boxView viewTap];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
